<template>
	<jk-dialog
		v-model="showDialog"
		:title="`${dataId ? '编辑' : '新增'}-区域区域`"
		width="800px"
		:show-content-loading="showLoading"
		:save-btn-loading="saveBtnLoading"
		append-to-body
		:show-confirm-btn="false"
		:show-save-btn="true"
		:permission-prefix="permissionPrefix"
		@on-cancel="onVisibleChange(false)"
		@on-visible-change="onVisibleChange"
		@on-save="onConfirmBtn('save')"
	>
		<el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="110px" :show-message="false">
			<el-row ref="box1">
				<el-col :span="8">
					<el-form-item class="margin-bottom-10" label="区域" prop="workshopId">
						<el-select v-model="ruleForm.workshopId" class="width-100-percent" placeholder="区域">
							<el-option
								v-for="item in workshopList"
								:key="item.id"
								:label="item.name"
								:value="item.id"
							></el-option>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item class="margin-bottom-10" label="区域编号" prop="code">
						<el-input v-model="ruleForm.code" placeholder="区域编号" />
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item class="margin-bottom-10" label="区域名称" prop="name">
						<el-input v-model="ruleForm.name" placeholder="区域名称" />
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<jk-table border :data="ruleForm.processList" :height="dialogTableHeight - 20">
			<vxe-column title="操作" align="center" field="processName" :width="90">
				<template slot="header">
					<el-button type="text" size="mini" @click="onAddBtn">添加</el-button>
				</template>
				<template slot-scope="scope">
					<el-button type="default" icon="el-icon-delete" size="mini" @click="ruleForm.processList.splice(scope.rowIndex, 1)"></el-button>
				</template>
			</vxe-column>
			<vxe-column title="工序" align="center" field="processName" :width="140">
				<template slot-scope="scope">
					<jk-select v-model="scope.row.processId" :option-list="processList" size="mini"></jk-select>
				</template>
			</vxe-column>
			<vxe-column title="机台明细" align="left" field="shiftName" :min-width="100">
				<template slot-scope="scope">
					<div class="flex-start-center-wrap">
						<div
							v-for="(item, index) in scope.row.machineList"
							:key="index"
							style="width: calc(100% / 6);padding: 1px;"
						>
							<el-tag class="width-100-percent flex-between-center" :closable="true" effect="plain" @close="ruleForm.processList[scope.rowIndex].machineList.splice(index, 1)">
								<span>{{ item.machineName }}</span>
							</el-tag>
						</div>
						<div style="padding: 1px;">
							<el-tag class="el-icon-plus flex-between-center" plain @click="onAddMachineBtn(scope)"></el-tag>
						</div>
					</div>
				</template>
			</vxe-column>
		</jk-table>
		<checkbox-machine-dialog
			:default-select-rows="selectRowMachineList"
			check-key-name="machineId"
			:dialog-state="selectMachineDialogState"
			@on-confirm="onConfirmBtnOfSelectMachineDialog"
			@on-visible-change="onVisibleChangeOfSelectMachineDialog"
		></checkbox-machine-dialog>
	</jk-dialog>
</template>

<script>
    import calHeight from '/src/mixins/cal-dialog-height';
    import {
        spinWorkshopAreaCreate,
        spinWorkshopAreaUpdate,
        spinWorkshopAreaGet
    } from '../../../api/basicData/workshopArea';
    import { spinProcessPage } from '../../../api/technology/process';
    import checkboxMachineDialog from '../../schedule/empMachine/components/checkbox-machine-dialog';
    export default {
        name: 'WorkshopArea',
        components: {
            checkboxMachineDialog
        },
        props: {
            // 页面权限的前缀
            permissionPrefix: {
                type: String,
                default: ''
            },
            dialogState: {
                type: Boolean,
                default: false
            },
            defaultTypeCode: {
                type: String,
                default: ''
            },
            dataId: {
                type: [String, Number],
                default: ''
            }
        },
        mixins: [calHeight],
        data() {
            return {
                selectMachineDialogState: false,
                workshopList: [],
                processList: [],
                showDialog: false,
                showLoading: true,
                saveBtnLoading: false,
                ruleForm: {
                    id: null,
                    code: '',
                    name: '',
                    workshopId: null,
                    processList: []
                },
                rules: {
                    code: [{ required: true, trigger: 'change' }],
                    name: [{ required: true, trigger: 'change' }],
                    colorValue: [{ required: true, trigger: 'change' }],
                    workshopId: [{ required: true, trigger: 'change' }]
                },
                selectRowIndex: null,
                selectRowMachineList: []
            };
        },
        methods: {
            onAddMachineBtn({ row, rowIndex }) {
                console.log(rowIndex);
                this.selectRowIndex = rowIndex;
                this.selectRowMachineList = JSON.parse(JSON.stringify(row.machineList));
                this.selectMachineDialogState = true;
            },
            onConfirmBtnOfSelectMachineDialog(arr) {
                if (arr.length) {
                    arr.forEach(x => {
                        this.ruleForm.processList[this.selectRowIndex].machineList.push({
                            machineId: x.id,
                            machineCode: x.code,
                            machineName: x.name
                        });
                    });
                }
                this.selectMachineDialogState = false;
            },
            onVisibleChangeOfSelectMachineDialog(e) {
                this.selectMachineDialogState = e;
            },
            onAddBtn() {
                this.ruleForm.processList.push({
                    processId: null,
                    processCode: null,
                    processName: null,
                    machineList: []
                });
            },
            getParamData() {
                const params = JSON.parse(JSON.stringify(this.ruleForm));
                const item = this.workshopList.find(x => x.id === params.workshopId) || {};
                params.workshopCode = item.code;
                params.workshopName = item.name;
                let processItem = {};
                params.processList.forEach(x => {
                    processItem = this.processList.find(k => k.id === x.processId) || {};
                    x.processCode = processItem.code;
                    x.processName = processItem.name;
                });
                return params;
            },
            createAndUpdateRequest() {
                this.saveBtnLoading = true;
                // 新增
                if (!this.dataId) {
                    this.ruleForm.id = null;
                    spinWorkshopAreaCreate(this.getParamData()).then(res => {
                        this.saveBtnLoading = false;
                        if (res.data.status === 200) {
                            this.$tipsBar(this, 'save');
                            // 生产订单-远程搜索组件用到，需返回ID
                            this.$emit('on-finish', res.data.res);
                        }
                    });
                    return;
                }

                // 编辑
                spinWorkshopAreaUpdate(this.getParamData()).then(res => {
                    this.saveBtnLoading = false;
                    if (res.data.status === 200) {
                        this.$tipsBar(this, 'save');
                        this.$emit('on-finish', res.data.res);
                    }
                });
            },
            onConfirmBtn(type) {
                this.$refs['ruleForm'].validate(valid => {
                    if (valid) {
                        this.createAndUpdateRequest();
                    } else {
                        this.$tipsBar(this, 'validator');
                    }
                });
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                if (!e) {
                    Object.assign(this.$data, this.$options.data());
                    this.$nextTick(() => {
                        this.$refs.ruleForm.resetFields();
                    });
                }
            },
            getDetailRequest() {
                return spinWorkshopAreaGet({ id: this.dataId }).then(res => {
                    if (res.data.status === 200) {
                        this.ruleForm = res.data.res;
                    }
                });
            },
            getProcessListRequest() {
                return spinProcessPage({ auditState: 1 }).then(res => {
                    if (res.data.status === 200) {
                        this.processList = res.data.res;
                    }
                });
            },
            async getDependentData() {
                this.showLoading = true;
                await this.getProcessListRequest();
                this.workshopList = this.$store.state.user.userWorkshop.workshopList;
                if (!this.dataId) this.$set(this.ruleForm, 'workshopId', this.$store.state.user.userWorkshop.defaultWorkshopId);
                if (this.dataId) await this.getDetailRequest();
                this.showLoading = false;
            }
        },
        watch: {
            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    this.getDependentData();
                }
            }
        }
    };
</script>
